<template>
  <div>
    <a-card :bordered="false">
      <s-table
        ref="table"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="action" slot-scope="text, record">
          <template>
            <!--4 为已完成-->
            <a v-if="record.status === 4" @click="handleDownload(record)">下载</a>
          </template>
        </span>
      </s-table>
    </a-card>
  </div>
</template>

<script>
import { Ellipsis, STable } from '@/components'
import { downloadAsyncExportTask, getAsyncExportTaskList } from '@/api/attachment'

const STATUS_MAP = {
  1: '初始化',
  2: '进行中',
  3: '已失败',
  4: '已完成'
}

export default {
  name: 'List',
  components: {
    STable,
    Ellipsis
  },
  data () {
    return {
      // 表头
      columns: [
        {
          title: '编号',
          dataIndex: 'task_numbering'
        },
        {
          title: '任务名称',
          dataIndex: 'task_name'
        },
        {
          title: '状态',
          customRender: record => STATUS_MAP[record.status]
        },
        {
          title: '创建时间',
          dataIndex: 'created_at'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getAsyncExportTaskList(parameter).then(res => {
          return res
        })
      }
    }
  },
  created () {

  },
  methods: {
    refreshList () {
      this.$refs.table.refresh()
    },
    handleDownload (record) {
      const hide = this.$message.loading('即将跳转新页面进入下载,务必让浏览器允许系统打开新页面,否则无法进入下载', 0)
      setTimeout(hide, 5000)
      downloadAsyncExportTask(record.id)
        .then(res => {
          if (!res.hasOwnProperty('url') || res.url.length === 0) {
            this.$notification.warn({
              message: '文件不存在或已过期删除'
            })
          } else {
            // 获取 oss 地址后 直接跳转下载
            res.hasOwnProperty('url') && res.url.length !== 0 && this.$message.info(h => {
              return h('span', {}, [
                '如没有成功跳转下载, 请直接点击链接前往下载: ',
                h('a', { attrs: { href: res.url } }, '跳转下载')
              ])
            })
            window.open(res.url)
          }
        })
        .catch(e => {
          this.$notification.error({
            message: e.message || '网络请求错误'
          })
        })
    }
  }
}
</script>
